package com.zjm.xml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.junit.Test;

import java.util.List;

/**
 * @author ZJM
 * @date 2024/4/7 22:25
 */
public class Dom4jTest02 {

    @Test
    public void test1() {
        SAXReader reader = new SAXReader();
        try {
            // 读取XML文件
            Document document = reader.read("src/main/resources/xml/blog.xml");
            // 获取根元素
            Element root = document.getRootElement();
            // 获取所有博客文章
            List<Element> postElements = root.elements("post");
            // 遍历每篇博客文章
            for (Element postElement : postElements) {
                System.out.println("Post ID: " + postElement.attributeValue("id"));
                System.out.println("Title: " + postElement.elementText("title"));
                System.out.println("Author: " + postElement.elementText("author"));
                System.out.println("Content: " + postElement.elementText("content"));
                System.out.println("Publish Date: " + postElement.elementText("publish_date"));
                // 获取评论列表
                Element commentsElement = postElement.element("comments");
                if (commentsElement != null) {
                    List<Element> commentElements = commentsElement.elements("comment");
                    // 遍历每条评论
                    System.out.println("评论的内容：");
                    for (Element commentElement : commentElements) {
                        System.out.println("Comment ID: " + commentElement.attributeValue("id"));
                        System.out.println("Author: " + commentElement.elementText("author"));
                        System.out.println("Content: " + commentElement.elementText("content"));
                        System.out.println("Publish Date: " + commentElement.elementText("publish_date"));
                        System.out.println();
                    }
                }
                System.out.println();
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }
}
